package com.doliere.android.app.wifidirectservice.sockets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.http.message.BufferedHeader;

import android.os.AsyncTask;

/**
 * 
 * @author doliere
 * String : the parameters passed to the execute method when creating a new instance of this class.
 * String : the type of parameters to be passed to publishProgress and received in onProgressUpdate
 * String : the type of the result when the doInBackground method ends its execution.
 * 
 * This class listens to other peers connection requests. 
 */
public class ServerSide extends AsyncTask<String, String, String>{
	
	private ServerSocket mServerSocket; // Référence vers la server Socket de l'application.
	private Socket mClient;
	
	private BufferedReader mIncomingMessagesBuffer; // Buffer where entring messages will be stored.
	private PrintWriter mOutGoingMessagesBuffer; // Buffer where out going messages are stored before being sent to clients.
	
	private final String SEND_MESSAGE = "SEND_MESSAGE";
	private final String RETREIVE_MESSAGE = "RETREIVE_MESSAGE";
	private final String ESTABLISH_CONNEXION = "ESTABLISH_CONNEXION";
	
	public ServerSide(ServerSocket serverSocket){
		mServerSocket = serverSocket;
	}
	
	
	
	/*
	 * This method waits until a connexion is asked. When the connexion is established, we can start communication(non-Javadoc)
	 * The parameters params will be a 2 field String..., the first once the type of action to be taken and the second
	 * parameter, the message to be sent, when it's about sending messages
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	
	@Override
	protected String doInBackground(String... params) {
		
        String request = params[0];
        String result = "";
  
        if(request.equals(ESTABLISH_CONNEXION)){
			try {
				mClient = mServerSocket.accept(); // Attente blocante d'une connexion.
				mIncomingMessagesBuffer = new BufferedReader(new InputStreamReader(mClient.getInputStream())); // Get the socket input stream.
				mOutGoingMessagesBuffer = new PrintWriter(new OutputStreamWriter(mClient.getOutputStream())); // Get the socket output stream.
				result = "Connexion successfully established";
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result = "An error occured when setting up connexion";
			}
			return result;
        }else if(request.equals(SEND_MESSAGE)){
        	result = params[1] == null ? "" : params[1]; // Get the message to be sent
        	mOutGoingMessagesBuffer.write(result);  // Send the message retreived.
        	return result + " successfully sent";
        }else if(request.equals(RETREIVE_MESSAGE)){
        	result = "";
        	try {
				while(mIncomingMessagesBuffer.read() != -1){
					result += mIncomingMessagesBuffer.readLine();
				}
				return result;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        return "No action to be executed";
	}
	
	
	//This method is called when publishProgress(String... args) is called within doInBackground.
	@Override
	protected void onProgressUpdate(String...progress){
		
	}
	
	//This method is called when the doInBackground method ends its execution.
	@Override
	protected void onPostExecute(String result){
		
	}
}
